package com.ele.server.dao;

import com.ele.model.Question;
import com.ele.model.QuestionUsage;

import java.util.List;

public class QuestionDAO extends GenericDAO<Question> {

    public QuestionDAO() {
        super(Question.class);
    }


    public Question getFirstUncompletedQuestion(Long sectionId) {
        List resultList = em.createNativeQuery(("SELECT * FROM question q" +
                " LEFT JOIN questionusage u ON u.QUESTION_ID = q.ID AND u.USER_ID" +
                " JOIN answer a ON a.QUESTION_ID = q.ID" +
                " WHERE q.SECTION_ID = :sectionId AND u.id IS NULL OR u.completed IS FALSE" +
                " GROUP BY q.ID ORDER BY RAND() LIMIT 1").replaceFirst(":sectionId", String.valueOf(sectionId)), Question.class)
                .getResultList();

        if (resultList.isEmpty()) {
            return null;
        } else {
            return serialize((Question) resultList.get(0));
        }
    }

    public QuestionUsage getUsage(Long userId, Long questionId) {
        List resultList = em.createNativeQuery("SELECT u.* FROM questionusage u WHERE u.user_id = :userId AND u.question_id = :questionId"
                .replaceFirst(":userId", String.valueOf(userId))
                .replaceFirst(":questionId", String.valueOf(questionId)),
                QuestionUsage.class).getResultList();

        if (resultList.isEmpty()) {
            return null;
        } else {
            return serialize((QuestionUsage) resultList.get(0));
        }
    }
}
